package com.zhou.pc;

public class A {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}
class Data{
    private int count = 0;
    private int bufferCount = 10;

    //判断等待,执行操作,通知线程
    //+1
    public synchronized void increment() throws InterruptedException {
        while(count >= bufferCount){
            this.wait();
        }
        count++;
        System.out.println(Thread.currentThread().getName()+"-->"+count);
        this.notifyAll();
    }
    //-1
    public synchronized void decrement() throws InterruptedException {
        while(count <= 0){
            this.wait();
        }
        count--;
        System.out.println(Thread.currentThread().getName()+"-->"+count);
        this.notifyAll();
    }
}